import numpy as np
import cv2

def fit_ellipse(points):
    """
    从正负事件图像中拟合椭圆
    """
    if len(points) < 100:
        return None
    try:
        ellipse = cv2.fitEllipseDirect(points)
        return ellipse
    except Exception as e:
        print(f"椭圆拟合失败: {e}")
        return None
    

def transform_points(points, ellipse):
    (x_center, y_center), (width, height), angle = ellipse
    
    # 创建变换矩阵
    angle_rad = np.deg2rad(angle)
    cos_angle = np.cos(angle_rad)
    sin_angle = np.sin(angle_rad)
    
    # 组合变换：旋转然后缩放
    transform_matrix = np.array([
        [2*cos_angle/width, 2*sin_angle/width],
        [-2*sin_angle/height, 2*cos_angle/height]
    ])
    
    # 中心化点集并应用变换
    centered_points = points - np.array([x_center, y_center])
    transformed_points = centered_points @ transform_matrix.T
    
    return transformed_points
    

def ellipse_fit_score(points, ellipse):
    """
    计算椭圆拟合分数
    """
    transformed_points = transform_points(points, ellipse)
    
    # 计算每个点到原点的距离
    distances = np.linalg.norm(transformed_points, axis=1)
    
    # 计算到单位圆圆周的绝对距离
    abs_distances_to_circle = np.abs(distances - 1.0)
    
    # 计算平均绝对距离
    mean_abs_distance = np.mean(abs_distances_to_circle)
    
    # 计算拟合分数
    fit_score = 1.0 - mean_abs_distance
    
    return fit_score
